//
//  LoginDetailViewController.m
//  fitnessmanage
//
//  Created by 众拳科技 on 2017/10/16.
//  Copyright © 2017年 zongquankeji. All rights reserved.
//

#import "LoginDetailViewController.h"
#import "LoginDetailView.h"
#import "MyTabBarViewController.h"
//#import <TLSSDK/TLSHelper.h>
//#import <TLSSDK/TLSLoginHelper.h>
#import "CZQSelctChoseView.h"

@interface LoginDetailViewController (){
    
    NSTimer *_timer;
    
    int _count;
}

@property(nonatomic,weak)LoginDetailView *loginDetailView;

@end

@implementation LoginDetailViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
            
    LoginDetailView *loginDetailView = [[LoginDetailView alloc] initWithFrame:self.view.frame];
    
    //密码明文暗文切换
    [loginDetailView.lookBtn addTarget:self action:@selector(passwordChange:)forControlEvents:UIControlEventTouchUpInside];
//
//    //登录按钮
    [loginDetailView.loginBtn addTarget:self action:@selector(loginBtnClick)forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:loginDetailView];
    
    self.loginDetailView = loginDetailView;
}


#pragma mark 获取验证码
-(void)sendVerCodeBtnClick:(UIButton *)sender{
    
    [self startTimerWithButton:sender];
}

//启动定时器
- (void)startTimerWithButton:(UIButton *)button
{
    button.enabled = NO;
    if (!_timer) {
        _timer = [[NSTimer alloc]initWithFireDate:[NSDate date] interval:1 target:self selector:@selector(count:) userInfo:button repeats:YES];
        [[NSRunLoop mainRunLoop]addTimer:_timer forMode:NSRunLoopCommonModes];
    }
}

//倒计时
- (void)count:(NSTimer *)timer
{
    UIButton *button = timer.userInfo;
    
    if (_count == 0) {
        button.enabled = YES;
        [_timer invalidate];
        _timer = nil;
        _count = 30;
    }
    _count --;    
    [button setTitle:[NSString stringWithFormat:@"再发一次 %d",_count] forState:UIControlStateDisabled];
}

#pragma mark 密码切换
-(void)passwordChange:(UIButton *)btn{
    
    btn.selected = !btn.selected;
    
    self.loginDetailView.passWordTF.secureTextEntry = !self.loginDetailView.passWordTF.secureTextEntry;
    
    NSString* text = self.loginDetailView.passWordTF.text;
    
    self.loginDetailView.passWordTF.text = @" ";
    
    self.loginDetailView.passWordTF.text = text;
}

#pragma mark 登录按钮点击
-(void)loginBtnClick{
    
    [self.view endEditing:YES];
    
    NSString *userAccount = self.loginDetailView.phoneTF.text;
    
    NSString *password = self.loginDetailView.passWordTF.text;
    
    if (userAccount.length == 0 || password.length == 0) {
        
        [MBProgressHUD showText:@"请输入账号和密码" toview:self.view];
        
        return;
    }
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [params setObject:userAccount forKey:@"username"];
    [params setObject:password forKey:@"password"];
    [params setObject:@0 forKey:@"IsThirdLogin"];
    [MBProgressHUD showMessage:@"" toView:self.view];
    
    [HTTPTool POSTRaw:Post_Login parameters:params

           success:^(id responseObject){

               [MBProgressHUD hideHUDForView:self.view];
               
               NSLog(@"%@",responseObject);

               //[[responseDirt objectForKey:@"code"] intValue] == 607
               if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {

                   NSMutableArray *brandList = [[NSMutableArray alloc] initWithArray:[responseObject objectForKey:@"BrandList"]];
                   

                   
                   loginUser *user = [loginUser mj_objectWithKeyValues:responseObject];
                   
                   [loginUser  saveUser:user];

                   NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];

                   

                   [userDefault setBool:YES forKey:@"isLogin"];
                   
                   [userDefault setValue:[responseObject objectForKey:@"MasterType"] forKey:@"MasterType"];
                   
                   [userDefault setValue:[responseObject objectForKey:@"Token"] forKey:@"Token"];

                   [userDefault setValue:[responseObject objectForKey:@"UserID"] forKey:@"UserID"];

                   [userDefault setValue:[responseObject objectForKey:@"TLSToken"] forKey:@"TLSToken"];
                   
                   [userDefault setValue:[responseObject objectForKey:@"ShopID"] forKey:@"ShopID"];
                   
                   [userDefault setValue:[responseObject objectForKey:@"SectID"] forKey:@"SectID"];

                   [userDefault setObject:password forKey:@"password"];

                   [userDefault setObject:userAccount forKey:@"username"];

                   [userDefault synchronize];

                   NSString *userId = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"TLSToken"]];


                   NSString *sign = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"SIG"]];

                   
//                   UIApplication *appDelegate = [UIApplication sharedAppDelegate];
                   MyTabBarViewController *myTabVC = [[MyTabBarViewController alloc] init];
                   
                   [UIApplication sharedApplication].keyWindow.rootViewController = nil; //
                   
                   [UIApplication sharedApplication].keyWindow.rootViewController = myTabVC;
                   
                   
                   
//                   if (user.ApplyShops.count > 0) {
//
//                       ApplyShops *shop = [ApplyShops mj_objectWithKeyValues:[user.ApplyShops lastObject]];
//
//                       [userDefault setBool:YES forKey:@"isCompleteInfo"];
//
//                       if ([shop.Status integerValue] == 0) {
//                           //审核中
//
//                           [JHSysAlertUtil presentAlertViewWithTitle:@"温馨提示" message:@"暂时无法使用，等待后台审核。" cancelTitle:@"取消" defaultTitle:@"退出" distinct:NO cancel:^{
//                               exit(0);
//                           } confirm:^{
//                               exit(0);
//                           }];
//
//                       }
//
//
//                   }
//                   else{
//
//                       [userDefault setBool:NO forKey:@"isCompleteInfo"];
//
//
//                       //读用户类型
//                       NSString *MasterType = [userDefault valueForKey:@"MasterType"];
//
//                       __weak typeof(self)weakSelf = self;
//
//
//                       //场馆，门派绑定
//
//                       if ([MasterType integerValue] == 1) {
//                           //师傅
//
//                           CZQSelctChoseView *SelctChoseView = [[CZQSelctChoseView alloc] init];
//
//                           SelctChoseView.urlString = Get_GetAllSectListData;
//
//                           SelctChoseView.commitBlock = ^(NSString *str) {
//
//                               CZQSelctChoseView *SelctChoseView1 = [[CZQSelctChoseView alloc] init];
//
//                               NSMutableDictionary *param = [NSMutableDictionary dictionary];
//
//
//                               SelctChoseView1.pandID = str;
//
//                               SelctChoseView1.urlString = @"";
//
//
//                               SelctChoseView1.commitBlock = ^(NSString *str) {
//
//
//
//                               };
//
//                               [SelctChoseView1 showWithAnimation];
//
//
//                           };
//
//                           [SelctChoseView showWithAnimation];
//
//                       }else
//                       {
//                           //教练
//
//                           CZQShopBandChoseView *sourceAlertView = [[CZQShopBandChoseView alloc] init];
//
//                           sourceAlertView.urlString = Get_Brand;
//
//                           sourceAlertView.commitBlock = ^(NSString *str) {
//
//                               CZQShopBandChoseView *shop = [[CZQShopBandChoseView alloc] init];
//
//                               NSMutableDictionary *param = [NSMutableDictionary dictionary];
//
//
//                               shop.pandID = str;
//
//                               shop.urlString = [NSString stringWithFormat:@"%@%@",Get_ShopList,str];
//
//
//                               shop.commitBlock = ^(NSString *str) {
//
//
//
//                               };
//
//                               [shop showWithAnimation];
//
//
//                           };
//
//                           [sourceAlertView showWithAnimation];
//
//                       }
//
                   
                    
                   
//               }
                   
                       
                   
//                   [self loginTim:userId andSign:sign];

               }
               else{

                   [MBProgressHUD showText:[responseObject objectForKey:@"Message"]];
               }

           }

           failure:^(NSError *error){

               [MBProgressHUD hideHUDForView:self.view];
               [MBProgressHUD showText:@"登录失败"];
           }];
    
}

-(void)enterMainUI{
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    
    BOOL isCompleteInfo = [userDefault boolForKey:@"isCompleteInfo"];
    
    //已经登录并且第一次已经完善了品牌信息和场地信息
//    if (isCompleteInfo) {
//
//        MyTabBarViewController *myTabVC = [[MyTabBarViewController alloc] initWithCompleteInfo:YES];
//
//        IMAAppDelegate *appDelegate = [IMAAppDelegate sharedAppDelegate];
//
//        appDelegate.window.rootViewController = nil;
//
//        appDelegate.window.rootViewController = myTabVC;
//
//        //[UIApplication sharedApplication].keyWindow.rootViewController = myTabVC;
//    }
//    else{
//
//        IMAAppDelegate *appDelegate = [IMAAppDelegate sharedAppDelegate];
//
//        MyTabBarViewController *myTabVC = [[MyTabBarViewController alloc] init];
//
//        [UIApplication sharedApplication].keyWindow.rootViewController = nil; //
//
//        appDelegate.window.rootViewController = myTabVC;
//
//    }
}


#pragma mark 登录腾讯IM
/**
 *  登录腾讯
 */
-(void)loginTim:(NSString *)userId andSign:(NSString *)sign{
    
//    TLSHelper *tlsHelper = [TLSHelper getInstance];
//
//    [tlsHelper TLSPwdLogin:userId andPassword:@"d762a41d9b599147" andTLSPwdLoginListener:self];
    
    __weak typeof(self) weakSelf = self;
    
//    IMALoginParam *loginParam = [[IMALoginParam alloc] init];
//    loginParam.identifier = userId;
//    loginParam.userSig = sign;
//    NSLog(@"loginParam.userSig = %@",loginParam.userSig);
//    loginParam.tokenTime = [[NSDate date] timeIntervalSince1970];
//
//    [IMAPlatform configWith:loginParam.config];
//
//    //直接登录
//    [[IMAPlatform sharedInstance] login:loginParam succ:^{
//
//        [weakSelf enterMainUI];
//
//    } fail:^(int code, NSString *msg) {
//
//        NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
//
//        [userDefault removeObjectForKey:@"Token"];
//
//        [userDefault removeObjectForKey:@"TLSToken"];
//
//        [userDefault removeObjectForKey:@"UserID"];
//
//        [userDefault removeObjectForKey:@"isLogin"];
//
//        [userDefault synchronize];
//
//        [MBProgressHUD showError:@"登录失败"];
//    }];forControlEvents:UIControlEventTouchUpInside
}

@end
